package com.rexolar.openapi.interceptor;

import com.rexolar.openapi.constants.Constants;
import com.rexolar.openapi.context.OpenContext;
import com.rexolar.openapi.context.OpenContextUtil;
import com.rexolar.openapi.enums.ErrorCodeEnum;
import com.rexolar.openapi.exception.IllegalRequestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author zhusiyu11000
 * @description: 参数长度截器
 * @date 2020-01-09
 **/

@Component
@Slf4j
public class ReqParamsInterceptor extends BaseOpenApiInterceptor {
    private static final int GET_PARAMS_LEN = 1024;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {

        if (skipCheckUri(httpServletRequest.getRequestURI())) {return true;}

        OpenContext openContext = OpenContextUtil.getContext();
        if (null == openContext) {
            openContext = OpenContextUtil.enter(httpServletRequest);
        }
        String requestMethod = httpServletRequest.getMethod();

        //如果get请求参数大于1024则返回提醒使用post请求提交
        if (Constants.HTTP_METHOD_GET.equals(requestMethod) && httpServletRequest.getQueryString()!=null && httpServletRequest.getQueryString().length() > GET_PARAMS_LEN) {
            throw new IllegalRequestException(ErrorCodeEnum.ILLEGAL_PARAMS_LEN_MORE_1024);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) {
        OpenContextUtil.exit();
    }

}